/************************权限资源管理js*********************************/
define(function(require, exports, module) {

	seajs.use(["jquery1.7","utils","bean/baseService", "bean/backManagerService","confirmbox","ui","zTree","ztree-exedit"], function($,utils,baseService,backManagerService,Confirmbox,ui) {
		
		var ctx = utils.constants.ctx;
		var Map=utils.Map;		
		var gradeConfirmbox;
		var gradeAddOrUp = 1;
		var grade_sort_id = 2; //分类2为年级
		var grade_url = ctx + "/back/base/group-json?sortId=" + grade_sort_id; 
		var updateGradeId = null;
		var form = layui.form;

		
		form.on('submit(grade_sumit)', function(data){
		
			if(data.field.id!=0){				
				backManagerService.groupUpdate(data.field);
				alert("修改成功！");
			}
			else {
				backManagerService.groupAdd(data.field);
				alert("添加成功！");
			}
			location.reload();
			return false;
	
		 });
		//zTree基本设置
		var grade_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				async : {
					enable : true,
					url : grade_url, 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					addHoverDom : addHoverDom_grade,
					removeHoverDom: removeHoverDom_grade,
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  

					onAsyncSuccess: zTreeOnAsyncSuccess_grade,
					onRightClick : addHoverDom_grade  
		        } 
		};

		//添加按钮图标事件
		function addHoverDom_grade(treeId,treeNode){

			//添加按钮
			var sObj = $("#" + treeNode.tId + "_span");
			if ($("#addBtn_"+treeNode.id).length>0) return;
			
			var addStr = "<span class='button add' id='addBtn_" + treeNode.id
				+ "' title='添加' onfocus='this.blur();'></span>";
			sObj.append(addStr);
			
			var btn = $("#addBtn_"+treeNode.id);
			if (btn) btn.bind("click", function(){
				var map = new Map();
				map.put("id", treeNode.id);
				map.put("submit", "groupAdd");
				showGradeWBox(map)
			});
			
			//修改按钮
			var editStr = "<span id='editBtn_" +treeNode.id+ "' class='button edit' id='editBtn_" + treeNode.id
			+ "' title='修改' onfocus='this.blur();'></span>";
			sObj.append(editStr);	
			
			btn = $("#editBtn_"+treeNode.id);
			
			if (btn) btn.bind("click", function(){
				
				var map = new Map();
				map.put("id", treeNode.id);
				map.put("pId", treeNode.parentId);
				map.put("name", treeNode.name);
				map.put("url", treeNode.url);
				map.put("method", treeNode.method);
				map.put("descn", treeNode.descn);
				map.put("orderId", treeNode.orderId);
				map.put("submit", "groupUpdate");
				showGradeWBox(map);
			});
			
			//删除按钮
			var editStr = "<span id='removeBtn_" +treeNode.id+ "' class='button remove' id='removeBtn_" + treeNode.id
			+ "' title='删除' onfocus='this.blur();'></span>";
			sObj.append(editStr);				
			btn = $("#removeBtn_"+treeNode.id);			
			if (btn) btn.bind("click", function(){
				gradeDelete(treeNode.id, treeNode.parentId);
		    })
		}
		//去掉按钮图标事件
		function removeHoverDom_grade(treeId, treeNode) {

			$("#addBtn_"+treeNode.id).unbind().remove();
			$("#editBtn_"+treeNode.id).unbind().remove();
			$("#removeBtn_"+treeNode.id).unbind().remove();
		};
		//加载数据成功后方法
		function zTreeOnAsyncSuccess_grade(){
			
			var zTree = $.fn.zTree.getZTreeObj("grade_tree");
			var nodes = zTree.getSelectedNodes();
			var grade_exNodeList = utils.cookide.getCookieValue("grade_exNodeList").split(',');

			for(var i=0; i < grade_exNodeList.length; i++) {

				zTree.expandNode(zTree.getNodeByParam("id", grade_exNodeList[i], null), true, false, true);
			}
			utils.cookide.setCookie("grade_exNodeList", [], 1, "/");
			ui.mask().hide();
		}

		//添加修改权限资源窗口
		function showGradeWBox(map){
			var flag = 0;
			if(map == null){
				map = new Map();
				map.put("submit", "groupAdd");			
			}
			if (map.container.submit == "groupAdd") {
				flag = 1;			
			}
			var gradeId = map.container.id;
			var parentId = map.container.pId;
			$.post('/back/base/gradeEdit/'+(typeof(gradeId)=="undefined"?0:gradeId),{"flag":flag,"parentId":parentId}, function(str){
			
				layer.open({
				    type: 1,
				    content: str //注意，如果str是object，那么需要字符拼接。
				  });
				  form.render();
			});
//			console.log(map);
		}

		
		//删除权限资源
		function gradeDelete(id, pId) {
			if(pId == null){
				var pId = 0;
			}
			layer.confirm('是否要删除这个类目', '确认删除框', function() {
				try {

					backManagerService.groupDelete(id);
					layer.alert("删除成功！");
					window.location.reload();
					
				} catch (e) {
					layer.alert("删除失败！</br>" + e.message);
				}
			});	
		}

		//显示右键菜单
		function showRMenu(type, x, y) {
			$("#grade_rMenu").show();
			if (type=="root") {
				$("#m_del").hide();
				$("#m_check").hide();
				$("#m_unCheck").hide();
			}
			$("#grade_rMenu").css({"top":y+"px", "left":x+"px", "display":"block"});
		}
		//隐藏右键菜单
		function hideRMenu() {
			$("#grade_rMenu").hide();
		}

	

		//排序树
		function moveGradeTree(treeNode1, treeNode2){
			
			var treeNodes = [
					{"id" : treeNode1.id,						
					"orderId" : treeNode2.orderId},
					{"id" : treeNode2.id,						
					"orderId" : treeNode1.orderId}		
			];
			
			try {

				baseService.updateOrder("groupManager", treeNodes);
				var zTree = $.fn.zTree.getZTreeObj("grade_tree");
				utils.cookide.setCookie("grade_exNodeList", treeNode1.parentId, 1, "/");
				zTree.reAsyncChildNodes(null, "refresh");
				
			} catch (e) {
				alert("移动失败！</br>" + e.message);
			}
		}
		
		var zNodes=[]; 
		hideRMenu();
		$.fn.zTree.init($("#grade_tree"), grade_setting, zNodes);

		$("#grade_tree").prev().unbind('click');
		$("#grade_tree").prev().bind('click', function(){
			showGradeWBox(null);
		});
		$("#grade_rMenu").hover( //鼠标离开右键菜单隐藏事件
				function () {		
				},
				function () {
					hideRMenu();
				}
		);
		
		var updateRolesCb;
		function showGradeRoles(gradeId, roleIds){
			
			updateGradeId = gradeId;
			var data = '<div id="grade_role_info" style="min-height: 100px;">';
			
			var roles;
			try{
				roles = backManagerService.loadAllroles();
			} catch (e) {
				blackBox.alert("加载数据失败:" + e.message);
				return;
			}
			
			for(var i=0;i<roles.length;i++) {
				
				var v = 20;
				if(roles[i].name != null && roles[i].name.length > 6) {
					v = 0;
				}
				var checked = '';
				if(roleIds.indexOf(roles[i].id) > -1) {
					checked = 'checked="checked"';
				}
				data += '<span style="overflow: hidden;margin-bottom:' + v + 'px;width: 100px;display: block;float: left;">' 
						+ '<input type="checkbox" ' + checked + ' name="grade_roles" id="grade_role_'
						+ roles[i].id + '">' + roles[i].name + '</span>';

			}
			data += '</div>'
			
			if(updateRolesCb == null) {
				updateRolesCb = new Confirmbox({
					
					trigger: '#grade_role_confirmbox',
					title: "分配角色",
					message: data,
					width : 450,
					onConfirm: function() {
			
						var ch = $('#grade_role_info input[name="grade_roles"]');
						var newRoleIds = []; //新角色ids
						
						for(var i=0; i<ch.length;i++) {

							if("checked" == ch.eq(i).attr("checked")) {
								var id = parseInt(ch.eq(i).attr("id").replace("grade_role_", ""));
								newRoleIds.push(id);
							}
						}
						
						try{

							backManagerService.groupAllotRole(updateGradeId, newRoleIds);
							blackBox.alert("分配角色成功！");
							this.hide();
							window.location.reload();
						} catch (e) {
							blackBox.alert("分配角色失败:" + e.message);
							return;
						}
					}
				});
			} else {					
				updateRolesCb.before('show',function() {

			       this.set('message', "");
			       this.set('message', data);		       
			   });
			}
			updateRolesCb.show();			
		}
	});

});

